<?php 
namespace app\api\controller;
use think\Db;
class Account extends Base{
	public function getList(){
		$page = $this->request->param('currentPage',1);
		$limit = $this->request->param('pageSize',10);
		$books_id = $this->request->param('books_id',0);
		$where = NULL;
		if($books_id){
			$where = 'books_id = '.$books_id;
		}else{
			$data['status'] = 1;
			$data['data'] = [];
			$data['count'] = 0;

			return returnJson(200,$data);
		}

		$list = db('account')->where($where)->page($page,$limit)->order(['create_time','id'=>'asc'])->select();
		$count = db('account')->where($where)->count();

		foreach ($list as $key => $value) {
			$list[$key]['create_time_str'] = date("Y-m-d H:i:s",$value['create_time']);
			$list[$key]['initial_money_str'] = number_format($value['initial_money'],2);
			$list[$key]['balance_str'] = number_format($value['balance'],2);
			$list[$key]['initial_money'] = (int)$value['initial_money'];
			$list[$key]['child'] = db('account')->where('pid = '.$value['id'])->count();
		}
		$data['status'] = 1;
		$data['data'] = $list;
		$data['count'] = $count;

		return returnJson(200,$data);
	}

	public function add(){
		if( $this->request->isAjax() || $this->request->isPost() ){
			$add['code'] = $this->request->param('code','trim');
			$add['name'] = $this->request->param('name','trim');
			$add['pid'] = $this->request->param('pid',0,'trim');
			$add['initial_money'] = $this->request->param('initial_money','0','trim');
			$add['balance'] = $this->request->param('initial_money','0','trim');
			$add['books_id'] = $this->request->param('books_id','trim');
			$add['create_time'] = time();
			$res = db('account')->insert($add);
			if($res !== false){
				$data['status'] = 1;
				$data['msg'] = '添加成功！';
				return returnJson(200,$data);
			}else{
				$data['status'] = 0;
				$data['msg'] = '添加失败！';
				return returnJson(200,$data);
			}
		}else{
			$books_id = $this->request->param('books_id',0);
			if($books_id){
				$account_list = db('account')->where('books_id = '.$books_id.' AND initial_money = 0')->select();
				$data['account_list'] = $account_list;
				return returnJson(200,$data);
			}else{
				$data['status'] = 1;
				$data['data'] = [];
				$data['count'] = 0;
				return returnJson(200,$data);
			}
		}
	}

	public function edit(){
		if( $this->request->isAjax() || $this->request->isPost() ){
			$upd['id'] = $this->request->param('id','trim');
			$upd['code'] = $this->request->param('code','trim');
			$upd['name'] = $this->request->param('name','trim');
			$upd['pid'] = $this->request->param('pid',0,'trim');
			$upd['books_id'] = $this->request->param('books_id','trim');
			$res = db('account')->update($upd);
			if($res !== false){
				$data['status'] = 1;
				$data['msg'] = '修改成功！';
				return returnJson(200,$data);
			}else{
				$data['status'] = 0;
				$data['msg'] = '修改失败！';
				return returnJson(200,$data);
			}
		}
	}
}